<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Models\YeepayBank;
use App\Models\YeepayDistrict;
use App\Services\AgentService;
use App\Services\ObsService;
use App\Utils\ShortUrl;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Symfony\Component\HttpFoundation\File\File;

class CommonController extends Controller
{
    /** @var ObsService */
    private $obsService;

    /** @var AgentService */
    private $agentService;

    /**
     * UploadController constructor.
     */
    public function __construct(ObsService $obsService, AgentService $agentService)
    {
        $this->obsService = $obsService;
        $this->agentService = $agentService;
    }

    /** 上传Base64格式的图片 */
    public function uploadBase64Image()
    {
        request()->validate([
            'image_type' => ['required', Rule::in(['id_card', 'avatar'])],
            'base64_str' => ['required'],
        ]);
        $file = $this->base64ToUploadedFile(request()->base64_str);
        $this->checkFile($file);
        $key = request()->image_type . '/' . uniqid();
        $imageUrl = $this->obsService->upload($key, $file);

        return [
            'image_url' => $imageUrl,
        ];
    }

    /** 上传图片至华为云 */
    public function uploadImage()
    {
        request()->validate([
            'image_type' => ['required', Rule::in(['id_card', 'avatar'])],
            'file' => ['required', 'image'],
        ]);
        $file = request()->file('file');
        $this->checkFile($file);
        $key = request()->image_type . '/' . uniqid();
        $imageUrl = $this->obsService->upload($key, $file);

        return [
            'image_url' => $imageUrl,
        ];
    }

    /** 查询省市区信息 */
    public function listDistricts()
    {
        if (request()->province_code) {
            return YeepayDistrict::query()
                ->when(request()->province_code, function ($q) {
                    return $q->where('province_code', request()->province_code);
                })
                ->select(['city_code', \DB::raw('max(city_name) as city_name')])
                ->groupBy('city_code')
                ->get()
                ->map(function (YeepayDistrict $district) {
                    return [
                        'code' => $district->city_code,
                        'name' => $district->city_name,
                    ];
                })->toArray();
        }
        if (request()->city_code) {
            return YeepayDistrict::query()
                ->when(request()->city_code, function ($q) {
                    return $q->where('city_code', request()->city_code);
                })
                ->select(['district_code', \DB::raw('max(district_name) as district_name')])
                ->groupBy('district_code')->get()
                ->map(function (YeepayDistrict $district) {
                    return [
                        'code' => $district->district_code,
                        'name' => $district->district_name,
                    ];
                })->toArray();
        }

        return YeepayDistrict::query()
            ->select(['province_code', \DB::raw('max(province_name) as province_name')])
            ->groupBy('province_code')
            ->get()
            ->map(function (YeepayDistrict $district) {
                return [
                    'code' => $district->province_code,
                    'name' => $district->province_name,
                ];
            })->toArray();
    }

    /** 查询开户总行列表 */
    public function listBanks()
    {
        return YeepayBank::all()->map(function (YeepayBank $bank) {
            return [
                'code' => $bank->code,
                'name' => $bank->name,
            ];
        });
    }

    /** 查询代理配置 */
    public function getAgentSettings()
    {
        request()->validate([
            'keys' => 'required',
        ]);
        $keys = explode(',', request()->keys);

        return $this->agentService->getAgentSettings(request()->agent_id, $keys);
    }

    //查询Banner列表
    public function listBanners()
    {
        return Banner::query()
            ->where('agent_id', request()->agent_id)
            ->orderByDesc('sequence')
            ->get()
            ->map(function (Banner $banner) {
                return [
                    'image_url' => $banner->image_url,
                    'jump_url' => $banner->jump_url,
                ];
            });
    }

    /** 短链接 */
    public function shortUrl($code)
    {
        return redirect()->away(ShortUrl::getRawUrl($code));
    }

    private function checkFile(UploadedFile $file)
    {
        if ($file->getSize() >= 1024 * 1024) {
            throw new ApiException('图片大小不能超过1M');
        }
        if (!in_array($file->getMimeType(), ['image/jpg', 'image/jpeg', 'image/png'])) {
            throw new ApiException('图片格式必须为jpg/jpeg/png');
        }
    }

    private function base64ToUploadedFile($base64File)
    {
        $fileData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64File));

        // save it to temporary dir first.
        $tmpFilePath = sys_get_temp_dir() . '/' . Str::uuid()->toString();
        file_put_contents($tmpFilePath, $fileData);

        // this just to help us get file info.
        $tmpFile = new File($tmpFilePath);

        return new UploadedFile(
            $tmpFile->getPathname(),
            $tmpFile->getFilename(),
            $tmpFile->getMimeType(),
            0,
            true // Mark it as test, since the file isn't from real HTTP POST.
        );
    }
}
